var table;
var userId;
var companyId;
var delFlag;
$(function () {
    initTable();

    $("#tr-select-all").on('click', function () {
        if ($(this).prop("checked")) {
            $('#table tbody .tr-checkbox:not(:checked)').click();
        } else {
            $('#table tbody .tr-checkbox:checked').click();
        }
    });

    $('#table tbody').on('click', '.tr-checkbox', function () {
        if ($(this).prop("checked")) {
            $(this).closest("tr").addClass("tr-selected");
        } else {
            $(this).closest("tr").removeClass("tr-selected");
        }
    });
});

//每次操作之后的查询
function queryData() {
    table.ajax.reload();
}

function nullToString(obj) {
    if (typeof (obj) == "undefined" || obj == null || obj === "") {
        return "";
    } else {
        return obj;
    }
}

function getParam(data) {
    var param = {};
    param.userName = $('#searchForName').val();
    param.draw = data.draw;
    param.size = data.length;
    param.current = (data.start / data.length) + 1;//当前页码
    return param;
}

//获取用户id
function getSelectTrId() {
    var factorId = [];
    $(".tr-selected").each(function () {
        var id = $(this).attr("data-user-id");
        factorId.push(id);
    });
    return factorId;
}

//初始化表格
function initTable() {
    table = $('#table').DataTable({
        deferRender: true,
        serverSide: true,
        searching: false,
        ordering: false,
        sort: true,
        searchDelay: 200,
        autoWidth: true,
        processing: true,
        pageLength: 20,
        pagingType: "full_numbers", //分页样式：simple,simple_numbers,full,full_numbers
        ajax: function (data, callback, settings) {
            $.ajax({
                type: "post",
                url: ctp + "/user/queryList",
                cache: false,
                data: JSON.stringify(getParam(data)),
                dataType: "json",
                contentType: "application/json",
                success: function (result) {
                    if (result.code == "200") {
                        var returnData = {};
                        returnData.draw = result.draw;//这里直接自行返回了draw计数器,应该由后台返回
                        returnData.recordsTotal = result.data.total;//返回数据全部记录
                        returnData.recordsFiltered = result.data.total;//后台不实现过滤功能，每次查询均视作全部结果
                        returnData.data = result.data.records;//返回的数据列表
                        callback(returnData);
                    } else {
                        alert(result.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("网络异常");
                }
            });
        },
        columnDefs: [
            {
                "defaultContent": "",
                "targets": "_all"
            }
        ],
        columns: [
            {
                "data": "rowNum",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return "<input type='checkbox' class='tr-checkbox' >";
                },
                "width": "35px"
            },
            {
                "data": 'loginName',
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return nullToString(data);
                }
            },
            {
                "data": "userName",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return nullToString(data);
                }
            },
            {
                "data": "userType",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return getUserTypeInfo(data);
                },
            },
            {
                "data": "email",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return nullToString(data);
                }
            },
            {
                "data": "phoneNumber",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return nullToString(data);
                }
            },
            {
                "data": "sex",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return getSexInfo(data)
                }
            }
            ,
            {
                "data": "status",
                "className": 'text-center',
                "render": function (data, type, full, meta) {
                    return getStatusInfo(data);
                }
            },
            {
                "data": "remark",
                "className": 'text-left',
                "render": function (data, type, full, meta) {
                    return nullToString(data);
                }
            }
        ],
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "每页 _MENU_ 项",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项。",
            "sInfoEmpty": "当前显示第 0 至 0 项，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页",
                "sJump": "跳转"
            },
            "oAria": {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        },
        dom: "<'#myTools.am-g'<'am-u-sm-3'<'am-btn-toolbar'<'#mybuttons.am-btn-group am-btn-group-xs'>>><'#mySearch.am-u-sm-6'><'am-u-sm-3'<'#query.am-input-group am-input-group-sm w100'>>>" +
            "t" +
            "<'am-g'<'am-u-sm-4'i><'am-u-sm-4'r><'am-u-sm-4'p>>",
        createdRow: function (row, data, dataIndex) {
            $(row).attr("data-user-id", data.userId);
            $(row).attr("data-company-id", data.companyId);
            $(row).attr("data-del-flag", data.delFlag);
            $(row).attr("data-password", data.password);
            $(row).attr("data-salt", data.salt);

        },
        initComplete: function () {
            $("#myTools").after("<br/>");
            $("#mybuttons").append('<button type="button" class="am-btn am-btn-default am-btn-success" id = "newUser"><span class="am-icon-plus"></span> 新增</button>');
            $("#mybuttons").append('<button type="button" class="am-btn am-btn-default am-btn-secondary" id = "updateUser"><span class="am-icon-save"></span> 修改</button>');
            $("#mybuttons").append('<button type="button" class="am-btn am-btn-default am-btn-danger"><span class="am-icon-trash-o"></span> 删除</button>');
            $("#mySearch").append('<div class="am-form-group"></div>');
            $("#query").append('<input type="text" class="am-form-field" id = "searchForName" placeholder="请输入用户名称"><span class="am-input-group-btn"><button class="am-btn  am-btn-default am-btn-success tpl-am-btn-success am-icon-search" id = "queryForName" type="button"></button></span>');

            //新增按钮
            $('#newUser').on("click", function () {
                $("#insertElement").modal({
                    relatedTarget: this,
                    closeViaDimmer: false, // 点击外部空白处不关闭弹窗
                    closeOnConfirm:false, // 返回信息提示也不关闭弹窗
                    keyboard: false, //按下esc键不会被关闭
                });
            });

            //保存  btn_save
            $('#updateUser').on("click", function () {
                updateUserData();
            });

            //删除  btn_deleteData
            $('.am-btn-danger').on("click", function () {
                deleteData();
            });

            //查询按钮
            $('#queryForName').on('click', function () {
                table.ajax.reload();
            })
        },
        drawCallback: function () {
            $("#table tbody tr").each(function () {
                var status = $(this).attr("data-status");
                $(this).find("td").each(function () {
                    var cellNum = table.cell(this).index().column;
                    var dataSrc = table.column(cellNum).dataSrc();
                    if (dataSrc != "rowNum") {
                        var data = nullToString(table.cell(this).data());
                        if (dataSrc == "sex") {
                            if (data == 0) {
                                $(this).html("男");
                            } else {
                                $(this).html("女");
                            }
                        } else if (dataSrc == "status") {
                            if (data == 0) {
                                $(this).html("删除");
                            } else {
                                $(this).html("正常");
                            }
                        } else if (dataSrc == "userType") {
                            if (data == 00) {
                                $(this).html("管理员");
                            } else {
                                $(this).html("测试");
                            }
                        } else {
                            $(this).html(data);
                        }
                    }
                });
            });

        }
    });
}

//删除方法
function deleteData() {
    var data = getSelectTrId();

    //先判断 是否勾选
    if (data.length == 0) {
        alert("请勾选需要删除的数据！！！");
    } else {
        $.ajax({
            type: "post",
            url: ctp + "/user/delete",
            cache: false,
            data: JSON.stringify(data),
            dataType: "json",
            contentType: "application/json",
            success: function (result) {
                if (result.code == "200") {
                    queryData();
                    alert("删除成功");
                } else {
                    alert(result.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("网络异常");
            }
        });
    }
}

//新增用户方法
function insertUserData() {
    if(checkEmail() == false){
        return;
    }else if (checkPhone() == false) {
        return;
    }else{
        var parm = {};
        parm.userId = userId;
        parm.companyId = companyId;
        parm.delFlag = delFlag;
        parm.loginName = $('#login_name').val();
        parm.userName = $('#user_name').val();
        parm.userType = $('#user_type').val();
        parm.email = $('#email').val();
        parm.phoneNumber = $('#phone_number').val();
        parm.sex = $('#sex').val();
        parm.password = $('#password').val();
        parm.status = $('#status').val();
        parm.remark = $('#remark').val();
        $.ajax({
            type: "post",
            url: ctp + "/user/registerUser",
            cache: false,
            data: JSON.stringify(parm),
            dataType: "json",
            contentType: "application/json",
            success: function (result) {
                if (result.code == "200") {
                    queryData();
                    alert("保存成功");
                    $("#insertElement").modal('close');
                    emptyData();
                } else {
                    alert(result.msg);
                    emptyData();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("网络异常");
            }
        });
    }

}

//性别标记：性别 0 男 1 女
function getSexInfo(obj) {
    if (obj == 0) {
        return "男";
    } else if (obj == 1) {
        return "女";
    }
}

//状态标记 0删除 1 正常
function getStatusInfo(obj) {
    if (obj == 0) {
        return "删除";
    } else if (obj == 1) {
        return "正常";
    }
}

//用户角色类型
function getUserTypeInfo(obj) {
    if (obj == 00) {
        return "管理员";
    } else if (obj == 01) {
        return "测试";
    }
}

//清空注册用户产生的信息
function emptyData() {
    $('#company_id').val('');
    $('#login_name').val('');
    $('#user_name').val('');
    $('#user_type').val('');
    $('#email').val('');
    $('#phone_number').val('');
    $('#sex').val('');
    $('#password').val('');
    $('#status').val('');
    $('#remark').val('');
}

//修改按钮处理
function updateUserData() {
    var row = {}; //获取选中行的所有数据
    //先判断 是否勾选
    var check = getSelectTrId();
    if (check.length != 1) {
        alert("请选中一条记录进行修改！！");
    } else {
        $(".tr-selected").each(function () {
            $(this).find("td:not(:first-child)>:input").blur();
            row['userId'] = $(this).attr("data-user-id");
            row['companyId'] = $(this).attr("data-company-id");
            row['delFlag'] = $(this).attr("data-del-flag");
            row['password'] = $(this).attr("data-password");
            row['salt'] = $(this).attr("data-salt");

            $(this).find("td").each(function () {
                var td = $(this)[0];
                var cellNum = table.cell(td).index().column;
                var dataSrc = table.column(cellNum).dataSrc();
                if (dataSrc != "rowNum") {
                    var data = table.cell(td).data();
                    row[dataSrc] = data;
                }
            });
        });
        //进行数据回显至模态框
        userId = row['userId'];
        companyId = row['companyId'];
        delFlag = row['delFlag'];
        $('#login_name').val(row['loginName']);
        $('#user_name').val(row['userName']);
        $('#user_type').val(row['userType']);
        $('#email').val(row['email']);
        $('#phone_number').val(row['phoneNumber']);
        $('#sex').val(row['sex']);
        $('#password').val('');
        $('#status').val(row['status']);
        $('#remark').val(row['remark']);

        $("#insertElement").modal();
    }
}

//校验邮箱格式
function checkEmail() {
    var flag = true;
    var email = $('#email').val();
    var pattern = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
    if (pattern.test(email) == false) {
        alert("输入邮箱格式有误！！！");
        flag = false;
    }
    return flag;
}

//校验手机号码
function checkPhone() {
    var flag = true;
    var pattern = /^1[34578]\d{9}$/;
    var phone = $('#phone_number').val();
    if (!(pattern.test(phone))) {
        alert("手机号码有误，请重填！！！");
        flag = false;
    }
    return flag;
}
